package qlsl.androiddesign.view.subview.activityview;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.photoselector.model.PhotoModel;
import com.photoselector.ui.PhotoSelectorActivity;
import com.qlsl.androiddesign.kuaiwa.R;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import qlsl.androiddesign.activity.commonactivity.PhotoAddActivity;
import qlsl.androiddesign.activity.subactivity.FirstCategoryActivity;
import qlsl.androiddesign.activity.subactivity.ShoppingReleaseActivity;
import qlsl.androiddesign.application.SoftwareApplication;
import qlsl.androiddesign.constant.BaseConstant;
import qlsl.androiddesign.constant.IntentCodeConstant;
import qlsl.androiddesign.entity.commonentity.FragmentArgs;
import qlsl.androiddesign.entity.otherentity.ShoppingDetail;
import qlsl.androiddesign.entity.otherentity.ThreeCategory;
import qlsl.androiddesign.entity.otherentity.ThreeCategory.RowsBean;
import qlsl.androiddesign.http.xutils.HttpProtocol;
import qlsl.androiddesign.http.xutils.Protocol.FileType;
import qlsl.androiddesign.listener.OnUploadFileListener;
import qlsl.androiddesign.manager.ActivityManager;
import qlsl.androiddesign.util.commonutil.FileNameUtils;
import qlsl.androiddesign.util.commonutil.Log;
import qlsl.androiddesign.view.baseview.FunctionView;

/**
 * 商品发布页<br/>
 * 需要传入的键：<br/>
 * 传入的值类型： <br/>
 * 传入的值含义：<br/>
 * 是否必传 ：
 */
public class ShoppingReleaseView extends FunctionView<ShoppingReleaseActivity> {

	private List<File> files = new ArrayList<File>();

	public ShoppingReleaseView(ShoppingReleaseActivity activity) {
		super(activity);
		setContentView(R.layout.activity_shopping_release);
	}

	protected void initView(View view) {
		setTitle("商家发布");
		reset();
	}

	public void reset() {
		Bundle bundle2 = activity.getIntent().getExtras();
		if (bundle2 != null) {
			if (ActivityManager.getInstance().previousActivity().getClass()
					.getName().contains("MemberProductActivity")) {
				FragmentArgs args = (FragmentArgs) bundle2
						.getSerializable("detail");
				if (args != null) {
					ShoppingDetail detail = (ShoppingDetail) args.get("data");
					showToast("商品id:" + detail.getGoodsid());
				}

			}
		}
	}

	public void onResume() {
		Bundle bundle = activity.getIntent().getBundleExtra("bundle");
		if (bundle != null) {
			ThreeCategory.RowsBean category = (RowsBean) bundle
					.getSerializable("category");
			TextView tv_type = findViewById(R.id.register_et_pwd);
			tv_type.setText("" + category.getSumciertype());
			tv_type.setTag(category);
		}
	}

	protected void initData() {

	}

	protected void initListener() {

	}

	public <T> void showData(T... t) {

	}

	public <T> void showNoData(T... t) {

	}

	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.choose_category:// 选择分类
			doClickChooseCategory();
			break;
		case R.id.email_sign_in_button:
			doClickPublishView();
			break;
		case R.id.choose_photo:
			// doClickSelectPhotoView();
			doClickAddPhotoView(view);
			break;

		}

	}

	@SuppressWarnings("unchecked")
	private void doClickAddPhotoView(View view) {
		List<File> files = (List<File>) view.getTag();
		Intent intent = new Intent(activity, PhotoAddActivity.class);
		if (files != null) {
			intent.putExtra("files", (Serializable) files);
		}
		startActivityForResult(intent,
				IntentCodeConstant.REQUEST_CODE_PHOTO_ADD);
	}

	private void doClickSelectPhotoView() {
		Intent intent = new Intent(activity, PhotoSelectorActivity.class);
		intent.putExtra(PhotoSelectorActivity.KEY_MAX, 10);
		intent.putExtra(PhotoSelectorActivity.KEY_SECOND_DIR,
				FileNameUtils.getAccountSecondDir());

		intent.putExtra(PhotoSelectorActivity.KEY_PREFIX_NAME,
				FileNameUtils.getAccountPrefixName(activity));
		startActivityForResult(intent,
				IntentCodeConstant.REQUEST_CODE_PHOTO_PICKED);

	}

	private void doClickChooseCategory() {
		Bundle bundle = new Bundle();
		bundle.putBoolean("ischoose", true);
		SoftwareApplication.getInstance().setBundle(bundle);
		startActivity(FirstCategoryActivity.class);
	}

	private void doClickPublishView() {
		String[] keys = new String[] { "name", "oldprice", "newprice",
				"points", "brands", "adapter", "homeofclaret", "factoryno",
				"remark", "guaranteemonth" };
		ViewGroup parent = (ViewGroup) getContentView().getChildAt(0);// getContentView()
																		// 找到ScrollView
																		// getContentView().getChildAt(0)找到LinearLayout
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		for (int childIndex = 2, childCount = parent.getChildCount() - 2; childIndex < childCount; childIndex++) {// childIndex过滤最后2个
			EditText et_content = (EditText) parent.getChildAt(childIndex)
					.findViewById(R.id.detail_address);
			if (childIndex == 5 || childIndex == 9) {
				continue;
			}
			if (TextUtils.isEmpty(et_content.getText().toString())) {
				showToast("请填写");
				return;
			}
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("key", keys[childIndex - 2]);
			map.put("value", et_content.getText().toString());
			list.add(map);
		}
		ThreeCategory.RowsBean categorys = (ThreeCategory.RowsBean) ((TextView) findViewById(R.id.register_et_pwd))
				.getTag();

		if (categorys != null) {
			HttpProtocol protocol = new HttpProtocol();
			protocol.setMethod("publishgoods");
			for (HashMap<String, String> map_value : list) {
				protocol.addParam(map_value.get("key"), map_value.get("value"));
			}
			protocol.removeUserParam();
			protocol.addParam("fuserid", BaseConstant.TOKEN);
			protocol.addParam(
					"type",
					(((Spinner) findViewById(R.id.spinner))
							.getSelectedItemPosition() + 1) + "");
			protocol.addParam("fsumcierid", categorys.getSumcierid());

			if (files.size() > 0) {
				setProgressBarText("正在发布");
				showProgressBar();
				protocol.uploadFiles(files, FileType.PICTURE, listener);
			} else {
				showToast("请上传图片");
			}
		} else {
			showToast("请选择分类");
		}

	}

	private OnUploadFileListener listener = new OnUploadFileListener() {

		public void onSuccess(JSONObject jo) {
			showToast("发布成功");
			activity.finish();
		}

	};

	@SuppressWarnings("unchecked")
	public void onActivityResultOld(int requestCode, int resultCode, Intent data) {
		if (requestCode == IntentCodeConstant.REQUEST_CODE_PHOTO_PICKED) {
			if (resultCode == Activity.RESULT_OK) {
				Bundle bundle = data.getExtras();
				if (bundle == null) {
					showToast("无法加载图片");
					return;
				}
				List<PhotoModel> selectPhotos = (List<PhotoModel>) bundle
						.getSerializable(PhotoSelectorActivity.KEY_RESULT);
				if (selectPhotos.size() > 0) {
					for (PhotoModel photoModel : selectPhotos) {
						files.add(new File(photoModel.getOriginalPath()));
					}
					((TextView) findViewById(R.id.number)).setText(selectPhotos
							.size() + "/10");
				}
			}
		}
	};

	@SuppressWarnings("unchecked")
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == IntentCodeConstant.REQUEST_CODE_PHOTO_PICKED) {
			if (resultCode == Activity.RESULT_OK) {
				Bundle bundle = data.getExtras();
				if (bundle == null) {
					showToast("无法加载图片");
					return;
				}
				List<PhotoModel> selectPhotos = (List<PhotoModel>) bundle
						.getSerializable(PhotoSelectorActivity.KEY_RESULT);
				if (selectPhotos.size() > 0) {
					String path = selectPhotos.get(0).getOriginalPath();
					cropPhoto(path);
				}
			}
		} else if (requestCode == IntentCodeConstant.CROP_PHOTO) {
			if (data == null) {
				return;
			}
			Bitmap bitmap = data.getExtras().getParcelable("data");
			File file = saveBitmapToFile(bitmap);
		} else if (requestCode == IntentCodeConstant.REQUEST_CODE_PUBLISH_TYPE) {
			if (data == null) {
				return;
			}
			String firstsection = data.getStringExtra("firstsection");
			String secondsection = data.getStringExtra("secondsection");
			TextView tv_select = ((TextView) findViewById(R.id.tv_select));
			tv_select.setText(firstsection + ">" + secondsection);
			tv_select.setTag(data);
		} else if (requestCode == IntentCodeConstant.REQUEST_CODE_PHOTO_ADD) {
			if (data == null) {
				return;
			}
			files = (List<File>) data.getSerializableExtra("files");
			View addPhotoView = findViewById(R.id.choose_photo);
			addPhotoView.setTag(files);
			((TextView) findViewById(R.id.number))
					.setText(files.size() + "/10");
		}
	};
}
